﻿<%@ WebHandler Language="C#" Class="RbSkillTargetEmpMaint" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;

/**
 * Description: 热表厂单元技能矩阵维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2025.6.18
 **/

public class RbSkillTargetEmpMaint : IHttpHandler
{
    public bool IsReusable { get { return false; } }
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    TreeObject t = new TreeObject();
    List<TreeObject> treeNodes = new List<TreeObject>();
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "isAlreadyExists":
                        r = isAlreadyExists(jObject);//校验是否存在
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "addItem":
                        r = addItem(jObject);//添加
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "updateStatus":
                        r = updateStatus(jObject);//更新启用状态
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "updateItem":
                        r = updateItem(jObject);//更新
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "deleteItem":
                        r = deleteItem(jObject);//删除
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getSkillTargetInfo":
                        r = getSkillTargetInfo(jObject);//查询指标信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getTeamEmpList":
                        r = getTeamEmpList(jObject);//查询班组下员工
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询数据
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT rt.id,rt.rbskilltargetmaintid,f.factoryname || '/' || wc.workcentername || '/' || te.teamname orginfo,
       rm.skilltargetname,e.fullname workerfullname,rt.processvalue,rt.notes,f.factoryid,wc.workcenterid,rm.teamid,
       e2.fullname createfullname,rt.createdate,e3.fullname lastchangefullname,rt.lastchangedate,rt.isuse,rt.employeeid,rm.skilltype
FROM rbskilltargetemp rt
INNER JOIN rbskilltargetmaint rm ON rm.id = rt.rbskilltargetmaintid
LEFT JOIN employee e ON e.employeeid = rt.employeeid
LEFT JOIN employee e2 ON e2.employeeid = rt.createemployeeid
LEFT JOIN employee e3 ON e3.employeeid = rt.lastchangeemployeeid
INNER JOIN team te ON te.teamid = rm.teamid
LEFT JOIN workcenter wc ON wc.workcenterid = te.workcenterid
LEFT JOIN factory f ON f.factoryid = wc.factoryid
WHERE 1=1
";
        //指标名称
        if (jObject["skilltargetname"] != null && jObject["skilltargetname"].ToString() != "")
        {
            sql += string.Format(" AND rm.skilltargetname LIKE '%{0}%'", jObject["skilltargetname"].ToString());
        }

        //指标类型
        if (jObject["skilltype"] != null && jObject["skilltype"].ToString() != "")
        {
            sql += string.Format(" AND rm.skilltype = '{0}'", jObject["skilltype"].ToString());
        }

        //姓名
        if (jObject["fullname"] != null && jObject["fullname"].ToString() != "")
        {
            sql += string.Format(" AND e.fullname LIKE '%{0}%'", jObject["fullname"].ToString());
        }
        
        //组织架构
        if (jObject["selectOrg"] != null && jObject["selectOrg"].ToString() != "")
        {
            JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
            if (selectOrg.Count == 3)
            {
                sql += string.Format(" AND te.teamid = '{0}'", selectOrg[2].ToString());
            }
            if (selectOrg.Count == 2)
            {
                sql += string.Format(" AND wc.workcenterid = '{0}'", selectOrg[1].ToString());
            }
            if (selectOrg.Count == 1)
            {
                sql += string.Format(" AND f.factoryid = '{0}'", selectOrg[0].ToString());
            }
        }

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //校验是否已存在
    Result isAlreadyExists(JObject obj)
    {
        string sql = @"SELECT * FROM rbskilltargetemp sk WHERE sk.rbskilltargetmaintid = '{0}' AND sk.employeeid = '{1}'";
        sql = string.Format(sql, obj["rbskilltargetmaintid"].ToString(), obj["employeeid"].ToString());

        if (obj["id"] != null && obj["id"].ToString() != "")
        {
            sql += string.Format(" AND sk.id <> '{0}'", obj["id"].ToString());
        }

        DataTable dt = dal.GetDataTable(sql);
        Result r = new Result();
        r.data = dt.Rows.Count > 0;
        r.total = dt.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //添加
    Result addItem(JObject jObject)
    {
        string sql = @"
INSERT INTO rbskilltargetemp(id,rbskilltargetmaintid,employeeid,processvalue,createemployeeid,isuse,notes,createdate)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}',sysdate)";

        string id = Guid.NewGuid().ToString();//唯一id
        string rbskilltargetmaintid = jObject["rbskilltargetmaintid"].ToString();//指标id
        string employeeid = jObject["employeeid"].ToString();//员工id
        string processvalue = jObject["processvalue"].ToString();//指标执行情况
        string createemployeeid = jObject["createemployeeid"].ToString();//创建人
        string notes = jObject["notes"].ToString();
        string isuse = "0";

        sql = string.Format(sql, id, rbskilltargetmaintid, employeeid, processvalue, createemployeeid, isuse, notes);
        int count = dal.ExecuteSql(sql);

        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //更新
    Result updateItem(JObject jObject)
    {
        string sql = @" 
UPDATE rbskilltargetemp t 
SET t.rbskilltargetmaintid = '{1}',t.employeeid = '{2}',t.processvalue='{3}',t.notes='{4}',t.lastchangeemployeeid = '{5}',t.lastchangedate = sysdate 
WHERE t.id='{0}' ";
        
        string id = jObject["id"].ToString();
        string rbskilltargetmaintid = jObject["rbskilltargetmaintid"].ToString();
        string employeeid = jObject["employeeid"].ToString();
        string processvalue = jObject["processvalue"].ToString();
        string notes = jObject["notes"].ToString();
        string lastchangeemployeeid = jObject["lastchangeemployeeid"].ToString();
        
        sql = string.Format(sql, id, rbskilltargetmaintid, employeeid, processvalue, notes, lastchangeemployeeid);
        int count = dal.ExecuteSql(sql);

        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //更新启用状态
    Result updateStatus(JObject jObject)
    {
        string sql = @"UPDATE rbskilltargetemp t SET t.isuse='{1}',t.lastchangeemployeeid = '{2}',t.lastchangedate = sysdate WHERE t.id='{0}' ";
        string isuse = "";
        if (jObject["isuse"] != null)
        {
            isuse = jObject["isuse"].ToString() == "True" ? "0" : "1";
        }

        string employeeid = "";
        if (jObject["employeeid"] != null)
        {
            employeeid = jObject["employeeid"].ToString();
        }

        sql = string.Format(sql, jObject["id"].ToString(), isuse, employeeid);
        int count = dal.ExecuteSql(sql);

        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //删除
    Result deleteItem(JObject jObject)
    {
        string sql = string.Format("DELETE rbskilltargetemp t where t.id = '{0}'", jObject["id"].ToString());
        int count = dal.ExecuteSql(sql);
        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getSkillTargetInfo(JObject obj)
    {
        string sql = @"SELECT mt.* FROM rbskilltargetmaint mt WHERE mt.isuse = 0 AND mt.teamid = '{0}'";
        sql = string.Format(sql, obj["teamid"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询班组下的员工列表
    Result getTeamEmpList(JObject obj)
    {
        string sql = @"
SELECT e.employeeid,e.fullname,t.teamid,t.teamname 
FROM teamemployee te
INNER JOIN team t ON te.teamid = t.teamid
INNER JOIN employee e ON e.employeeid = te.employeeid
WHERE te.teamid = '{0}'";
        sql = string.Format(sql, obj["teamid"].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = dt.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}